using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

[assembly: WebResource("ScriptControls.AjaxLogin.js", "text/javascript")]

namespace Samples
{
	public class AjaxLogin : Login, IScriptControl
	{
        private void AddControlIDToScript(ScriptComponentDescriptor descriptor, string id)
        {
	        Control control = this.FindControl(id);
        	
	        if (control != null)
	        {
		         descriptor.AddElementProperty(id, control.ClientID);
	        }
            else
	        {
	            throw new NullReferenceException("Unable to find a control with the given ID.");
	        }
        }

        protected override void OnPreRender(EventArgs e)
        {
	        base.OnPreRender(e);

            ScriptManager manager;
            manager = ScriptManager.GetCurrent(this.Page);

            if (manager == null)
                throw new InvalidOperationException("A ScriptManager is required on the page.");
            
	        manager.RegisterScriptControl(this);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);

            ScriptManager.GetCurrent(this.Page).RegisterScriptDescriptors(this);
        }

        public IEnumerable<ScriptDescriptor> GetScriptDescriptors()
        {
	        ScriptControlDescriptor descriptor = new ScriptControlDescriptor("Samples.AjaxLogin", this.ClientID);
	        AddControlIDToScript(descriptor, "UserName");
	        AddControlIDToScript(descriptor, "Password");
	        AddControlIDToScript(descriptor, "RememberMe");
	        AddControlIDToScript(descriptor, "LoginButton");

	        yield return descriptor;
        }

        public IEnumerable<ScriptReference> GetScriptReferences()
        {
	        yield return new ScriptReference(Page.ClientScript.GetWebResourceUrl(typeof(AjaxLogin),
                "ScriptControls.AjaxLogin.js"));
        }
	}
}
